using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Eneta.Portal.Forum.Common.Controls;
using Eneta.Portal.Forum.Controls.Base;
using Eneta.Portal.Forum.Controls.Common;
using Eneta.Portal.Forum.Core.Domain.Entities;
using Eneta.Portal.Forum.Core.Service.Application;
using Microsoft.SharePoint;
using FredCK.FCKeditorV2;

namespace Eneta.Portal.Forum.Controls
{
    public class UpdateMessage : BaseForumControl
    {
        //private OWSForm _form;
        private HtmlGenericControl _form;
        //private OWSLabelField _lblSubject;
        //private OWSTextField _txtSubject;
        //private OWSSubmitButton _btnPost;
        //private OWSSubmitButton _btnCancel;
        //private OWSRichTextField _txtBody;

        private Label _lblSubject;
        private TextBox _txtSubject;
        private Button _btnPost;
        private Button _btnCancel;
        //private TextBox _txtBody;
        private FCKeditor _txtBody;

        private string _postModeTitle = "Vasta";

        #region Constructors

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (SPContext.Current.Web.CurrentUser == null)
            {
                Page.Response.Redirect("/_layouts/Eneta.Portal.Authentication/LiveAuthHandler.aspx?action=login&ReturnUrl=" + HttpUtility.UrlEncode(Page.Request.RawUrl));
                //HttpContext.Current.Response.Redirect("/foorum/", false);
                return;
            }

            var preview = (ForumsPostsViewControl)Page.LoadControl("~/_CONTROLTEMPLATES/ForumsPostsViewControl.ascx");
            var forumRep = new ForumRepository(SPContext.Current.Web);
            var postId = 0;
            object ds = null;
            if (int.TryParse(HttpContext.Current.Request["post"], out postId))
            {
                var post = forumRep.GetForumPostById(postId);
                ds = new[] { post };
            }
            if (ds == null)
            {
                var topic = forumRep.GetForumTopicById(_topicID);
                ds = new[] { topic.Starter };
            }
            preview.DataSource = ds;
            
            Controls.AddAt(0, preview);
        }

        /// <summary>
        /// Notifies server controls that use composition-based implementation to create any child
        /// controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                var topicName = string.Empty;

                //_form = new OWSForm(); //new OWSForm();
                _form = new HtmlGenericControl("span");
                _form.Attributes["style"] = "float:left;display:inline;width:628px";
                Controls.Add(_form);

                //_form.Controls.Add(BuildBasePageLinks());
                _form.Controls.Add(new LiteralControl("<br>"));

                _form.Controls.Add(new LiteralControl("<table class=post-table cellspacing=1 cellpadding=4 width=100% align=center style=\"display:table\">"));
                _form.Controls.Add(new LiteralControl("<tr>"));
                //if (HttpContext.Current.Request["postMethod"].ToLower() != "reply")
                //{
                //    _form.Controls.Add(
                //        new LiteralControl(string.Format("<td class=ms-ToolPaneTitle align=middle colspan=2>{0}</td>",
                //                                         _postModeTitle)));
                //}
                _form.Controls.Add(new LiteralControl("</tr>"));
                //_lblSubject = new OWSLabelField {Text = "Subject:"};
                _lblSubject = new Label { Text = "Pealkiri:", ID="lblSubject" };
                _lblSubject.Attributes["style"] = "display:inline";

                //_txtSubject = new OWSTextField
                //                  {
                //                      ID = "txtSubject", 
                //                      NumLines = 1
                //                  };
                _txtSubject = new TextBox {ID = "txtSubject", Columns=60};

                
                if (MessageMode != PostMode.New)
                {
                    _lblSubject.Visible = false;
                    _txtSubject.Text = topicName;
                    _txtSubject.Visible = false;



                    //preview.DataSource = ds;
                    //Controls.AddAt(0, preview);
                }

                //CreatePreviewSection();                               
                CreateMessageBodySection();                
                CreateButtonSection();
                _form.Controls.Add(new LiteralControl("</table>"));
                                
                //Controls.Add(new LiteralControl("</table>"));
            }
            catch (Exception ex)
            {
                WebPartParent.AddError(ex);
            }
        }

        /// <summary>
        /// Handles the Click event of the btnPost control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks>
        /// TODO move all this crap logic to the repository or somewhere... bad bad bad
        /// </remarks>
        private void BtnPostClick(object sender, EventArgs e)
        {

            if (SPContext.Current.Web.CurrentUser == null)
            {
                HttpContext.Current.Response.Redirect("/foorum/", false);
                return;
            }

            Topic parentTopic;
            var listItemId = 0;

            if (MessageMode == PostMode.Edit)
            {
                parentTopic = RepositoryRegistry.TopicRepository.GetById(_topicID);
                listItemId = _messageID;
            }
            else if (MessageMode == PostMode.New)
            {
                parentTopic = new Topic(_forumID, _txtSubject.Text);
                parentTopic.LastPost = DateTime.Now;
                parentTopic.TopicStarterId = ForumApplication.Instance.SpUser.ID;
                _topicID = RepositoryRegistry.TopicRepository.Save(parentTopic);
                WebPartParent.TopicCount++;
            }
            else
            {
                parentTopic = RepositoryRegistry.TopicRepository.GetById(_topicID);
            }

            string messageTitle;
            if(MessageMode == PostMode.New)
                messageTitle = _txtSubject.Text;
            else
                messageTitle = string.Format("RE: {0}", parentTopic.Name);

            var message = new Message(_topicID);
            message.Name = HttpUtility.HtmlEncode(messageTitle);
            message.Id = listItemId;
            //message.Body = HttpUtility.HtmlEncode(_txtBody.Text).Replace("\n", "<br/>");
            //message.Body = HttpUtility.HtmlEncode(_txtBody.Value).Replace("\n", "<br/>");
            message.Body = _txtBody.Value;
            message.UserId = ForumApplication.Instance.SpUser.ID;
            message.Author = ForumApplication.Instance.CurrentUser;
            message.ForumId = parentTopic.ForumId;

            var post = new ForumPostDto();
            post.AuthorUserName = ForumApplication.Instance.SpUser.LoginName;
            post.Body = message.Body;
            post.ForumId = parentTopic.ForumId;
            post.Title = messageTitle;
            post.TopicId = _topicID;

            var forumrep = new ForumRepository(SPContext.Current.Web);
            forumrep.SaveForumPost(post);

            //RepositoryRegistry.MessageRepository.Save(message);

            // Increase the post count in the main web part
            WebPartParent.PostCount++;
            WebPartParent.PersistProperties();

            // Increase the number of posts for this user
            message.Author.NumPosts++;
            RepositoryRegistry.ForumUserRepository.Save(message.Author);

            // Redirect to the new post
            var url = ForumApplication.Instance.GetLink(SharePointForumControls.ViewMessages, "topic={0}", _topicID);
            Page.Response.Redirect(url);
        }

        /// <summary>
        /// Handles the Click event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnCancelClick(object sender, EventArgs e)
        {
            string url;

            if (MessageMode == PostMode.New)
            {
                url = ForumApplication.Instance.GetLink(SharePointForumControls.ViewTopics, "forum={0}", _forumID);
            }
            else
            {
                url = ForumApplication.Instance.GetLink(SharePointForumControls.ViewMessages, "topic={0}", _topicID);
            }

            Page.Response.Redirect(url);
        }

        private void CreateMessageBodySection()
        {
            _form.Controls.Add(new LiteralControl("<tr>"));
            _form.Controls.Add(new LiteralControl("<td valign=top align=right>"));
            if (string.IsNullOrEmpty(_lblSubject.ID))
                _lblSubject.ID = "_lblSubject";
            _form.Controls.Add(_lblSubject);
            _form.Controls.Add(new LiteralControl("</td>"));
            
            _form.Controls.Add(new LiteralControl("<td>"));
            _form.Controls.Add(_txtSubject);
            _form.Controls.Add(new LiteralControl("</td>"));

            _form.Controls.Add(new LiteralControl("<tr>"));
            var lblMessage = new Label {Text = "Teade:", ID="lblMessage"};
            lblMessage.Attributes["style"] = "display:inline";
            _form.Controls.Add(new LiteralControl("<td valign=top align=right>"));
            _form.Controls.Add(lblMessage);
            _form.Controls.Add(new LiteralControl("</td>"));

            _form.Controls.Add(new LiteralControl("<td>"));            

            _txtBody = new FCKeditor
                           {
                               ID="txtBody", 
                               BasePath="/_layouts/fckeditor/",
                               Height=new Unit(260, UnitType.Pixel)
                           };

            _form.Controls.Add(_txtBody);

            _form.Controls.Add(new LiteralControl("</td>"));
            _form.Controls.Add(new LiteralControl("</tr>"));
        }

        private void CreatePreviewSection()
        {
            if(_messageID != 0 && MessageMode == PostMode.Reply)
            {
                _form.Controls.Add(new LiteralControl("<tr>"));
                _form.Controls.Add(new LiteralControl("<td valign=top align=right>"));
                _form.Controls.Add(new LiteralControl("<div class=\"ms-formdescription\" valign=top align=left>Preview:</div>"));
                _form.Controls.Add(new LiteralControl("</td>"));
                _form.Controls.Add(new LiteralControl("<td>"));
                Message message = RepositoryRegistry.MessageRepository.GetById(_messageID);
                string messageDisplay = string.Format("<strong>Vastus teatele: #{0}:</strong><br>{1}", _messageID, message.Body);
                _form.Controls.Add(new LiteralControl(messageDisplay));
                _form.Controls.Add(new LiteralControl("</td>"));
                _form.Controls.Add(new LiteralControl("</tr>"));
            }
        }
		
        private void CreateButtonSection()
        {
            _form.Controls.Add(new LiteralControl("<tr>"));
            _form.Controls.Add(new LiteralControl("<td align=center colspan=2>"));

            _form.Controls.Add(new LiteralControl("&nbsp;"));

            //_btnPost = new OWSSubmitButton();
            _btnPost = new Button();
            _btnPost.Click += BtnPostClick;
            _btnPost.Text = "Saada";
            _btnPost.ID = "btnPost";
            _form.Controls.Add(_btnPost);

            _form.Controls.Add(new LiteralControl("&nbsp;"));
            _form.Controls.Add(new LiteralControl("&nbsp;"));
            _form.Controls.Add(new LiteralControl("&nbsp;"));

            //_btnCancel = new OWSSubmitButton();
            _btnCancel = new Button();
            _btnCancel.Click += BtnCancelClick;
            _btnCancel.Text = "Loobu";
            _btnCancel.ID = "btnCancel";
            _form.Controls.Add(_btnCancel);

            _form.Controls.Add(new LiteralControl("</td>"));
            _form.Controls.Add(new LiteralControl("</tr>"));
        }
    }
}